package karaokit.com;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.farng.mp3.id3.ID3v1;

import karaokit.com.KaraoKitEngine.SearchType;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class FileBrowser extends ListActivity {
	private boolean afterFileWasClicked = false;
	private static KaraoKitEngine KarEngine = KaraoKitEngine.GetEngine();
	private enum DISPLAYMODE{ ABSOLUTE, RELATIVE; }	

	private final DISPLAYMODE displayMode = DISPLAYMODE.RELATIVE;
	private List<String> directoryEntries = new ArrayList<String>();
	private File currentDirectory = new File(KaraoKitEngine.KaraoKitDir);
	private SearchType curSearchType;
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (curSearchType == SearchType.Lyrics)
		{
			curSearchType = SearchType.Media;
			KarEngine.setSearchType(curSearchType);
		}
		
	}
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		afterFileWasClicked = false;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		browseTo(currentDirectory);
	}
	
	/**
	 * This function browses up one level
	 * according to the field: currentDirectory
	 */
	private void upOneLevel(){
		if(this.currentDirectory.getParent() != null)
			this.browseTo(this.currentDirectory.getParentFile());
	}

	private void browseTo(final File aDirectory){
		if (aDirectory.isDirectory()){
			Toast.makeText(this, aDirectory.getAbsolutePath(), Toast.LENGTH_SHORT).show();
			this.currentDirectory = aDirectory;
			KaraoKitEngine.KaraoKitDir = aDirectory.getAbsolutePath();
			curSearchType =  KarEngine.getSearchType();
			if (KarEngine.getSearchType() == SearchType.Media)
				fill(aDirectory.listFiles(KaraoKitEngine.MediaFilesFilter));
			else
				fill(aDirectory.listFiles(KaraoKitEngine.LyricsFilter));
		} 
		else {	
			
			
			
			OnClickListener AutoSearchYesListener = new OnClickListener(){
				public void onClick(DialogInterface arg0, int arg1) {
					try {
						HandleAutoSearchForLyrics();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
			
			OnClickListener AutoSearchNoListener = new OnClickListener(){
				
				OnClickListener browseForLyricsButtonListener = new OnClickListener(){				
					public void onClick(DialogInterface arg0, int arg1) {					
						KarEngine.fileSelected(FileBrowser.this, aDirectory, false);					
						KarEngine.setSearchType(SearchType.Lyrics);
						/*Intent i = new Intent(FileBrowser.this, FileBrowser.class);
						FileBrowser.this.startActivity(i);*/
						FileBrowser.this.browseTo(aDirectory.getParentFile());
					}
				};
				OnClickListener noLyricsButtonListener = new OnClickListener(){				
					public void onClick(DialogInterface arg0, int arg1) {					
						KarEngine.fileSelected(FileBrowser.this, aDirectory, true);
					}
				};
				OnClickListener cancelButtonListener = new OnClickListener(){
					public void onClick(DialogInterface arg0, int arg1) {
						// Do nothing
					}
				};
				
				public void onClick(DialogInterface arg0, int arg1) {

					new AlertDialog.Builder(FileBrowser.this)
					.setTitle("Question")
					.setMessage("Do you want to browse for lyrics too?\n")
					.setPositiveButton("Sure", browseForLyricsButtonListener)
					.setNeutralButton("No thanks", noLyricsButtonListener)
					.setNegativeButton("Cancel", cancelButtonListener)
							.show();
				}
			};

			if ((KarEngine.getSearchType() == SearchType.Media) && afterFileWasClicked){
				new AlertDialog.Builder(FileBrowser.this)
				.setTitle("Auto Search Lyrics")
				.setMessage("Do you want me to try and find the lyrics?")
				.setPositiveButton("Yes", AutoSearchYesListener)
				.setNegativeButton("No", AutoSearchNoListener)
				.show();
				KarEngine.fileSelected(FileBrowser.this, aDirectory, false);
				
			}
			else  {// the user chose a lyric file and is ready to play 
				KarEngine.fileSelected(FileBrowser.this, aDirectory, true);
			}
		}
	}
	
	private File SelectedLyricsFile;
	private File[] files;
	private int SelectedFileIndex;
	private void HandleAutoSearchForLyrics() throws IOException
	{
		curSearchType = SearchType.Lyrics;
		KarEngine.setSearchType(curSearchType);
		
		files = FileBrowser.this.currentDirectory.listFiles(KaraoKitEngine.LyricsFilter);
		/*ID3v1 prop = KarEngine.getMediaProperties();
		String album = prop.getAlbumTitle();
		String artist = prop.getArtist();
		String title = prop.getSongTitle();*/
		
		OnClickListener ContinueWithLyricsFileListener = new OnClickListener(){				
			public void onClick(DialogInterface arg0, int arg1) {			
				
				KarEngine.fileSelected(FileBrowser.this, files[SelectedFileIndex], true);
			}
		};
		
		OnClickListener DontContinueWithLyricsFileListener = new OnClickListener(){				
			public void onClick(DialogInterface arg0, int arg1) {					
				browseTo(currentDirectory);
			}
		};
		
		//String[] vals = title.split(" ");
		
		SelectedFileIndex = KaraoKitEngine.FindLyricsFileIndexByCurrentMediaFile(FileBrowser.this.currentDirectory);
		
		if (SelectedFileIndex > -1)
		{
			new AlertDialog.Builder(FileBrowser.this)
			.setTitle("Continue With Lyrics")
			.setMessage("Should I continue with the lyrics file:\n" + 
					files[SelectedFileIndex].getCanonicalPath())
			.setPositiveButton("Yep", ContinueWithLyricsFileListener)
			.setNegativeButton("Nope", DontContinueWithLyricsFileListener)
					.show();;
		}
		else
		{
			Toast.makeText(this, "Unable to find any lyrics files", Toast.LENGTH_LONG).show();
			Intent i = new Intent(FileBrowser.this, FileBrowser.class);
			FileBrowser.this.startActivity(i);
		}
	}
	
	
	
	
	
	@Override
	protected void onResume() {
		super.onResume();
	//	KarEngine.setSearchType(curSearchType);
		KarEngine.setCurLyrics(null);
		Toast.makeText(this, "Browsing for " + curSearchType, Toast.LENGTH_SHORT).show();
		this.browseTo(currentDirectory);
	}
		
	private void fill(File[] files) {
		this.directoryEntries.clear();
		// Add the "." and the ".." == 'Up one level'
		try {
			Thread.sleep(10);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		this.directoryEntries.add(".");

		if(this.currentDirectory.getParent() != null)
			this.directoryEntries.add("..");

		switch(this.displayMode){
		case ABSOLUTE:
			for (File file : files){
				this.directoryEntries.add(file.getPath());
			}
			break;
		case RELATIVE: // On relative Mode, we have to add the current-path to the beginning
			int currentPathStringLenght = this.currentDirectory.getAbsolutePath().length();
			for (File file : files){
				this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLenght));
			}
			break;
		}

		ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
				R.layout.file_row, this.directoryEntries);

		this.setListAdapter(directoryList);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		int selectionRowID = position;//(int) this.getSelectedItemPosition();//this.getSelectionRowID();  
		String selectedFileString = this.directoryEntries.get(selectionRowID);
		if (selectedFileString.equals(".")) {			
			this.browseTo(new File("/")); // go to root
		} else if (selectedFileString.equals("..")){
			this.upOneLevel();
		} else {
			File clickedFile = null;
			switch(this.displayMode){
			case RELATIVE:
				clickedFile = new File(this.currentDirectory.getAbsolutePath()
						+ this.directoryEntries.get(selectionRowID));
				break;
			case ABSOLUTE:
				clickedFile = new File(this.directoryEntries.get(selectionRowID));
				break;
			}
			if (clickedFile != null)
				afterFileWasClicked = true;
				this.browseTo(clickedFile);
		}
	}
}